﻿<%@ import namespace="System"%>
<%@ import namespace="System.IO"%>
<%@ import namespace="System.Drawing"%>
<%@ import namespace="System.Drawing.Imaging"%>
<script language="vb" runat="server">
 Sub Page_Load(Sender as object,e as eventargs)
    'RndNum是一个自定义函数
    dim VNum as string=RndNum(4)
    Session("VNum")=VNum
    ValidateCode(VNum)
 End Sub
 '生成图象验证码函数
    Sub ValidateCode(ByVal VNum)
        
        Dim Img As System.Drawing.Bitmap
        Dim g As Graphics
        Dim ms As MemoryStream
        Dim gheight As Integer = Int(Len(VNum) * 11.5)
        'gheight为图片宽度,根据字符长度自动更改图片宽度
        Img = New Bitmap(gheight, 20)
        g = Graphics.FromImage(Img)    'Arial
        g.DrawString(VNum, (New Font("white", 10)), (New SolidBrush(Color.Blue)), 3, 3) '在矩形内绘制字串（字串，字体，画笔颜色，左上x.左上y）
        ms = New MemoryStream()
        Img.Save(ms, ImageFormat.Png)
        Response.ClearContent() '需要输出图象信息 要修改HTTP头
        Response.ContentType = "image/Png"
        Response.BinaryWrite(ms.ToArray())
        g.Dispose()
        Img.Dispose()
        Response.End()
    End Sub
  '--------------------------------------------
  '函数名称:RndNum
  '函数参数:VcodeNum--设定返回随机字符串的位数
  '函数功能:产生数字和字符混合的随机字符串
  Function RndNum(VcodeNum)
    dim Vchar as string="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z"
    dim VcArray() as string=split(Vchar,",") '将字符串生成数组
    dim VNum as string=""
    dim i as byte
    For i=1 to VcodeNum
      Randomize
      VNum=VNum & VcArray(Int(35*Rnd)) '数组一般从0开始读取，所以这里为35*Rnd
    Next
    Return VNum
  End Function
</script>